package com.ztom.v2;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ZhangTao
 */
public class Code57LetterCombinationsOfAPhoneNumber {

    public List<String> letterCombinations(String digits) {
        if (digits == null || digits.length() == 0) {
            return new ArrayList<>();
        }

        String[] phoneMap = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
        List<String> res = new ArrayList<>();
        dfs(phoneMap, digits, 0, new StringBuilder(), res);
        return res;
    }

    public void dfs(String[] phoneMap, String digits, int index, StringBuilder combination, List<String> res) {
        if (index == digits.length()) {
            res.add(combination.toString());
            return;
        }

        // 从当前位置出发全排列
        String letters = phoneMap[digits.charAt(index) - '0'];
        for (int i = 0; i < letters.length(); i++) {
            // 取当前字符
            combination.append(letters.charAt(i));
            dfs(phoneMap, digits, index + 1, combination, res);
            // 回溯
            combination.deleteCharAt(index);
        }
    }
}
